package com.lv.filter;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;


import com.lv.data.Result;
import com.lv.enums.ResultEnum;
import com.lv.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Set;

@Component
@RefreshScope
public class TokenFilter implements GlobalFilter, Ordered {

    @Autowired
    private JwtUtil jwtUtil;

    @Value("#{'${gateway.exclusions.url}'.empty ? null : '${gateway.exclusions.url}'.split(',')}")
    private Set<String> urls;

    private PathMatcher pathMatcher = new AntPathMatcher();
    //过滤器
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //通过请求头 取出token
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        //先判断请求路径是否需要校验token
        for (String eurl : urls) {
            if (pathMatcher.match(eurl,path)){
                return chain.filter(exchange);
            }
        }

        String token = request.getHeaders().getFirst("AutharizeToken");
        //如果token不存在说明没登录
        if (token == null || "".equals(token)){
            return response(exchange);
        }
        //如果token存在 校验token

        try {
            jwtUtil.parseJwt(token);
        }catch (Exception e){
            return response(exchange);
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    //封装
    private Mono<Void> response(ServerWebExchange exchange){
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        //这里在返回头添加编码，否则中文会乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        byte[] bytes = JSONObject.toJSONBytes(Result.response(ResultEnum.TOKEN_NO), SerializerFeature.WriteMapNullValue);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(buffer));
    }
}
